package com.apollow.oschina.util;

import android.content.Context;
import android.text.TextUtils;
import android.widget.ImageView;

import java.io.File;

import it.sephiroth.android.library.picasso.MemoryPolicy;
import it.sephiroth.android.library.picasso.NetworkPolicy;
import it.sephiroth.android.library.picasso.Picasso;
import it.sephiroth.android.library.picasso.RequestCreator;

/**
 * Created by bobo on 2017/1/15.
 */

public class PicassoUtil {
    public static void displayImage(Context context, String url,
                                    int defaultDrawableId, ImageView userPhoto) {
        if (TextUtils.isEmpty(url)) {
            userPhoto.setImageResource(defaultDrawableId);
        } else if (url.startsWith("http")) {
            getPicasso(context, url, defaultDrawableId).into(userPhoto);
        } else if (url.startsWith("/")) {
            File file = new File(url);
            showUserPhoto(context, file, defaultDrawableId, userPhoto);
        }
    }

    public static RequestCreator getPicasso(Context context, String url,
                                            int loadingResId) {
        RequestCreator requestCreator = Picasso.with(context).load(url);
        if (loadingResId > 0) {
            return requestCreator.error(loadingResId).placeholder(loadingResId);
        } else {
            return requestCreator;
        }
    }

    private static void showUserPhoto(Context context, File file,
                                      int defaultDrawableId, ImageView imageView) {
        if (file == null || !file.exists()) {
            imageView.setImageResource(defaultDrawableId);
            return;
        }
//        Picasso.with(context).load(file).error(defaultDrawableId)
//                .placeholder(defaultDrawableId)
//                .into(imageView);
        //解决修改头像缓存造成的失败
        Picasso.with(context).load(file)
                .memoryPolicy(MemoryPolicy.NO_CACHE)
                .networkPolicy(NetworkPolicy.NO_CACHE)
                .error(defaultDrawableId)
                .into(imageView);
    }
    //调用方法
    //PicassoUtil.displayImage(context, url,defaultDrawableId, userPhoto);
}
